//
// Created by francklinson on 2021/10/23 AT 20:27.
//

#include <cstdlib>
#include <iostream>
#include <vector>

struct Object {
    int x, y, z;
};

struct MemoryRecorder {
    uint32_t memory_newed;
    uint32_t memory_deleted;

    uint32_t CurrentMemoryUsage() {
        return memory_newed - memory_deleted;
    }

    void ShowMemoryUsage() {
        std::cout << CurrentMemoryUsage() << " bytes used!" << std::endl;
    }

};

static MemoryRecorder mr;

// 重载new运算符 记录heap上的分配信息
void *operator new(size_t size) {
    std::cout << "Allocating " << size << " bytes" << std::endl;
    mr.memory_newed += size;
    return malloc(size);
}

// 重载delete
void operator delete(void *memory, size_t size) {
    mr.memory_deleted += size;
    std::cout << "Freeing memory:" << memory << " for " << size << " bytes!" << std::endl;
    free(memory);
}

int main() {
    mr.ShowMemoryUsage();
    std::string str = "Francklinson";
    mr.ShowMemoryUsage();
    {
        Object *obj = new Object();
        delete obj;
        std::unique_ptr<Object> uniptr = std::make_unique<Object>();
        std::vector<int> v{1, 2, 3, 4};
    }
    mr.ShowMemoryUsage();
    return 0;
}

